using Common.Core.Extension;
using Common.Extension;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.ObjectModel;

namespace AzrngTools.ViewModels.Other
{
    /// <summary>
    /// 今日新闻
    /// </summary>
    public partial class TodayNewsPageViewModel : ViewModelBase
    {
        private readonly HttpClient _httpClient;
        private readonly ILogger<TodayNewsPageViewModel> _logger;

        public TodayNewsPageViewModel(IHttpClientFactory factory, ILogger<TodayNewsPageViewModel> logger)
        {
            _logger = logger;
            _httpClient = factory.CreateClient();
            NewsItems = new ObservableCollection<string>();

            CurrDate = DateTime.Now.ToStandardString("yyyy-MM-dd");
        }

        /// <summary>
        /// 当前时间
        /// </summary>
        [ObservableProperty]
        private string _currDate;

        /// <summary>
        /// 农历
        /// </summary>
        [ObservableProperty]
        private string _chineseCalendar;

        /// <summary>
        /// 列表
        /// </summary>
        [ObservableProperty]
        private ObservableCollection<string> _newsItems;

        /// <summary>
        /// 处理
        /// </summary>
        [RelayCommand]
        private async Task Handle()
        {
            await FetchNewsFromApiAsync();
        }

        /// <summary>
        /// 获取新闻内容
        /// </summary>
        /// <returns></returns>
        private async Task FetchNewsFromApiAsync()
        {
            try
            {
                _httpClient.DefaultRequestHeaders.Add("Origin", "https://www.qqsuu.cn");
                _httpClient.DefaultRequestHeaders.Add("Referer", "https://www.qqsuu.cn/css/font-awesome.min.css");
                _httpClient.DefaultRequestHeaders.Add("User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0");

                var response = await _httpClient.GetAsync("https://udp.qqsuu.cn/apis/60s/60s.php?type=json");
                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    var newsResult = JsonConvert.DeserializeObject<NewResult<GetNewsDto>>(content);
                    if (newsResult.code != 200)
                        return;

                    foreach (var news in newsResult.data.news)
                    {
                        NewsItems.Add(news);
                    }

                    ChineseCalendar = newsResult.data.date_info.lunar_calendar;
                }
            }
            catch (Exception ex)
            {
                // 处理异常
                _logger.LogError(ex, $"异常 ：{ex.GetExceptionAndStack()}");
            }
        }
    }
}